<?php

namespace App\Http\Controllers;

use App\Http\Helpers\StatusResponse;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Models\Classify;

class ClassifyController extends Controller
{
    // 查询分类
    public function getAll () :JsonResponse
    {
        return $this->success(Classify::query()->get());
    }

    // 添加分类
    public function insert () : JsonResponse
    {
        // 分类名称
        $name = \request('name');
        // 分类简介
        $description = \request('description');
        if (!$this->isAdmin()) {
            return $this->failWithArr(StatusResponse::PERMISSION_REQUIRE);
        }
        if (Classify::query()->create([
            'name' => $name,
            'description' => $description
        ])) {
            return $this->success();
        }
        return $this->unknown_err();
    }

    // 删除分类
    public function delete ($id) : JsonResponse
    {
        // 检查权限
        if (!$this->isAdmin()) {
            return $this->failWithArr(StatusResponse::PERMISSION_REQUIRE);
        }
        // 查询分类
        if (!$classify = Classify::query()->find($id)) {
            return $this->failWithArr(StatusResponse::NOT_FOUND);
        }
        // 删除分类
        if ($classify->delete()) {
            return $this->success();
        }
        return $this->unknown_err();
    }
}
